package com.bilibili.server.service;

import com.bilibili.server.repository.VideoRepository;
import com.bilibili.server.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;
import java.util.logging.Logger;

@Service
public class ViewCountUpdateService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private VideoRepository videoRepository;

    private static final Logger logger = Logger.getLogger(ViewCountUpdateService.class.getName());

    // 每10分钟执行一次批量更新
    @Scheduled(fixedRate = 600000)
    @Transactional
    public void batchUpdateViewCounts() {
        logger.info("开始批量更新视频观看次数");
        
        // 获取待更新的视频ID列表
        Set<Long> videoIds = redisUtil.getPendingViewUpdates();
        
        if (videoIds.isEmpty()) {
            logger.info("没有待更新的视频观看次数");
            return;
        }
        
        logger.info("待更新视频数量: " + videoIds.size());
        
        // 遍历所有待更新的视频ID
        for (Long videoId : videoIds) {
            try {
                // 1. 获取Redis中的计数器值
                Integer viewCount = redisUtil.getVideoViewCount(videoId);
                
                if (viewCount != null && viewCount > 0) {
                    logger.info("[缓存调试] 批量更新视频" + videoId + "的观看次数: " + viewCount);
                    
                    // 2. 更新数据库中的观看次数
                    videoRepository.incrementViewCount(videoId, viewCount);
                    
                    // 3. 清除视频详情缓存，确保下次请求获取最新数据
                    String cacheKey = "video:detail:" + videoId;
                    redisUtil.deleteCache(cacheKey);
                    
                    // 4. 重置Redis计数器
                    redisUtil.resetVideoViewCount(videoId);
                    
                    logger.info("[缓存调试] 视频" + videoId + "观看次数更新成功，已清除缓存");
                }
            } catch (Exception e) {
                logger.severe("更新视频" + videoId + "观看次数失败: " + e.getMessage());
                // 继续处理下一个视频
            }
        }
        
        logger.info("视频观看次数批量更新完成");
    }
}
